<template>
  <div class="template-list">
    <el-card class="template-card">
      <template #header>
        <div class="card-header">
          <span>通知模板管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">添加模板</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="templateList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="模板代码" width="150" />
        <el-table-column prop="name" label="模板名称" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getNotificationTypeTag(scope.row.type)">
              {{ formatNotificationType(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="channel" label="渠道" width="120">
          <template #default="scope">
            {{ formatChannel(scope.row.channel) }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题模板" show-overflow-tooltip />
        <el-table-column prop="isActive" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
              {{ scope.row.isActive ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑模板对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="templateFormRef"
        :model="templateForm"
        :rules="templateRules"
        label-width="120px"
      >
        <el-form-item label="模板代码" prop="code">
          <el-input v-model="templateForm.code" placeholder="请输入模板代码，如：COURSE_BOOKING_SUCCESS" :maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称" :maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input v-model="templateForm.content" type="textarea" :rows="6" :maxlength="500" show-word-limit />
        </el-form-item>
        <el-form-item label="启用状态" prop="isActive">
          <el-switch v-model="templateForm.isActive" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看模板详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="模板详情"
      width="800px"
    >
      <el-form label-width="120px">
        <el-form-item label="模板代码">
          <span>{{ currentTemplate.code }}</span>
        </el-form-item>
        <el-form-item label="模板名称">
          <span>{{ currentTemplate.name }}</span>
        </el-form-item>
        <el-form-item label="通知类型">
          <el-tag :type="getNotificationTypeTag(currentTemplate.type)">
            {{ formatNotificationType(currentTemplate.type) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="推送渠道">
          {{ formatChannel(currentTemplate.channel) }}
        </el-form-item>
        <el-form-item label="标题模板">
          <span>{{ currentTemplate.title }}</span>
        </el-form-item>
        <el-form-item label="内容模板">
          <div class="template-content">{{ currentTemplate.content }}</div>
        </el-form-item>
        <el-form-item label="变量说明">
          <div class="template-variables">
            <el-tag
              v-for="variable in currentTemplate.variables"
              :key="variable"
              type="info"
              style="margin-right: 10px; margin-bottom: 10px;"
            >
              {{ variable }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-tag :type="currentTemplate.isActive ? 'success' : 'danger'">
            {{ currentTemplate.isActive ? '启用' : '禁用' }}
          </el-tag>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type {
  NotificationTemplate,
  CreateTemplateRequest,
  UpdateTemplateRequest
} from '@/types/api/notification'
import { templateApi } from '@/api/modules/notification'
import { preventDuplicateSubmit, formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const templateList = ref<NotificationTemplate[]>([])

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const templateFormRef = ref()
const currentTemplateId = ref(0)
const currentTemplate = ref<NotificationTemplate>({
  id: 0,
  code: '',
  name: '',
  type: 'COURSE',
  channel: 'ALL',
  title: '',
  content: '',
  variables: [],
  isActive: true
})

// 表单数据
const templateForm = reactive({
  code: '',
  name: '',
  type: 'COURSE',
  channel: 'ALL',
  title: '',
  content: '',
  variablesStr: '',
  isActive: true
})

// 表单验证规则
const templateRules = {
  code: [
    { required: true, message: '请输入模板代码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择通知类型', trigger: 'change' }
  ],
  channel: [
    { required: true, message: '请选择推送渠道', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入标题模板', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容模板', trigger: 'blur' }
  ]
}

// 获取模板列表
const getTemplateList = async () => {
  try {
    loading.value = true
    const res = await templateApi.getTemplateList({
      page: pagination.page,
      pageSize: pagination.pageSize
    })

    const data = res.data.data
    templateList.value = data.list
    pagination.total = data.total
  } catch (error) {
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新列表
const refreshList = () => {
  getTemplateList()
}

// 添加模板
const handleAdd = () => {
  dialogTitle.value = '添加模板'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑模板
const handleEdit = (row: NotificationTemplate) => {
  dialogTitle.value = '编辑模板'
  isEdit.value = true
  currentTemplateId.value = row.id
  Object.assign(templateForm, {
    code: row.code,
    name: row.name,
    type: row.type,
    channel: row.channel,
    title: row.title,
    content: row.content,
    variablesStr: row.variables.join(','),
    isActive: row.isActive
  })
  dialogVisible.value = true
}

// 查看模板详情
const handleView = (row: NotificationTemplate) => {
  currentTemplate.value = row
  detailDialogVisible.value = true
}

// 删除模板
const handleDelete = async (row: NotificationTemplate) => {
  formUtils.handleDeleteConfirm('这个模板', async () => {
    await templateApi.deleteTemplate(row.id)
    refreshList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 保存模板
const handleSave = async () => {
  if (!templateFormRef.value) return

  try {
    await templateFormRef.value.validate()

    // 使用防重复提交保护
    const submitKey = isEdit.value ? `update_template_${currentTemplateId.value}` : 'create_template'

    await preventDuplicateSubmit(submitKey, async () => {
      saveLoading.value = true
      try {
        if (isEdit.value) {
          // 编辑模板
          const updateData: UpdateTemplateRequest = {
            code: templateForm.code,
            name: templateForm.name,
            type: templateForm.type as 'COURSE' | 'CARD' | 'SYSTEM' | 'OTHER',
            channel: templateForm.channel as 'INTERNAL' | 'SMS' | 'EMAIL' | 'PUSH' | 'ALL',
            title: templateForm.title,
            content: templateForm.content,
            variables: templateForm.variablesStr ? templateForm.variablesStr.split(',').map(v => v.trim()) : [],
            isActive: templateForm.isActive
          }
          await templateApi.updateTemplate(currentTemplateId.value, updateData)
        } else {
          // 创建模板
          const createData: CreateTemplateRequest = {
            code: templateForm.code,
            name: templateForm.name,
            type: templateForm.type as 'COURSE' | 'CARD' | 'SYSTEM' | 'OTHER',
            channel: templateForm.channel as 'INTERNAL' | 'SMS' | 'EMAIL' | 'PUSH' | 'ALL',
            title: templateForm.title,
            content: templateForm.content,
            variables: templateForm.variablesStr ? templateForm.variablesStr.split(',').map(v => v.trim()) : []
          }
          await templateApi.createTemplate(createData)
        }

        ElMessage.success(`${isEdit.value ? '更新' : '创建'}成功`)
        dialogVisible.value = false
        refreshList()
      } catch (error: any) {
        ElMessage.error(`${isEdit.value ? '更新' : '创建'}失败`)
        throw error // 重新抛出错误以确保防重复提交正确处理
      } finally {
        saveLoading.value = false
      }
    })
  } catch (error: any) {
    // 防重复提交保护捕获的错误
    if (error.message === '请勿重复提交') {
      ElMessage.warning('请勿重复提交')
    }
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(templateForm, {
    code: '',
    name: '',
    type: 'COURSE',
    channel: 'ALL',
    title: '',
    content: '',
    variablesStr: '',
    isActive: true
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
  formUtils.resetForm(templateFormRef.value, templateForm)
}

// 分页相关方法
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getTemplateList()
}

const handleCurrentChange = (val: number) => {
  pagination.page = val
  getTemplateList()
}

// 格式化通知类型
const formatNotificationType = (type: string) => {
  const typeMap: Record<string, string> = {
    'COURSE': '课程',
    'CARD': '会员卡',
    'SYSTEM': '系统',
    'OTHER': '其他'
  }
  return typeMap[type] || type
}

// 获取通知类型标签
const getNotificationTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    'COURSE': 'success',
    'CARD': 'warning',
    'SYSTEM': 'danger',
    'OTHER': 'info'
  }
  return tagMap[type] || 'info'
}

// 格式化渠道
const formatChannel = (channel: string) => {
  const channelMap: Record<string, string> = {
    'INTERNAL': '站内信',
    'SMS': '短信',
    'EMAIL': '邮件',
    'PUSH': 'APP推送',
    'ALL': '全部渠道'
  }
  return channelMap[channel] || channel
}

// 生命周期
onMounted(() => {
  getTemplateList()
})
</script>

<style scoped>
.template-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.template-content {
  white-space: pre-wrap;
  line-height: 1.5;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.template-variables {
  padding: 10px 0;
}
</style>
